<template>
  <div class="edu-page-warp">
    <condition-card @reset="reset" @search="onSubmit" label-width="60px">
        <el-row :gutter="24" style="height: 50px;">
          <el-col :span="8">
            <el-form-item label="学院:">
              <el-select v-model="queryForm.department" @change="changeFaculty" style="width: 80%;">
                <el-option v-for="item in options.college" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业:">
              <el-select v-model="queryForm.subject" style="width: 80%;">
                <el-option v-for="item in options.speciality" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年级:">
              <el-select v-model="queryForm.grade" style="width: 80%;">
                <el-option v-for="item in options.grade" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
    </condition-card>
    <el-card>
      <div class="edu-page-title">导师列表</div>
      <div class="edu-opertion-bar" style="margin-bottom:16px;">
        <div class="float-left">
          <el-input type="text" v-model="queryForm.teacherId" placeholder="工号、姓名" size="mini" @keyup.enter.native="filter">
                <i class="el-icon-search" slot="suffix" style="margin-top:7px;cursor: pointer;" @click="filter">
                </i>
              </el-input>
        </div>
        <div class="float-right">
                <el-button @click="autoAssignTeacher" v-if="functions['automatic_allocation']" size="mini">自动分配</el-button>
                <el-button @click="exportFromExcel" v-if="functions['import_teacher']" size="mini">导入</el-button>
                <el-button @click="exportToExcel" size="mini">导出</el-button>
                <div style="display:none">
                  <input type="file" name="file" id="fileUp" @change="handleUpload()" />
                </div>
              </div>
      </div>
          <el-row :gutter="0" class="no-margin">
            <el-col>
              <el-table :data="teachers" size="mini" @selection-change="chooseTeacher" @expand-change="expandChange" ref="teacherTable">
                <el-table-column type="expand" width="50">
                  <template slot-scope="props">
                    <el-form label-position="right" inline class="edu-row-expand-4" label-width="90px">
                      <el-row :gutter="0">
                        <el-col :span="6">
                          <el-form-item label="工号">
                            <span>{{ props.row.teacherId }}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="姓名">
                            <span>{{ props.row.name }}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="学院">
                            <span>{{props.row.department}}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="专业">
                            <span>{{props.row.subject}}</span>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="0">
                        <el-col :span="6">
                          <el-form-item label="性别">
                            <span>{{ props.row.sex }}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="年级">
                            <span>{{ props.row.grade }}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="计划人数">
                            <span>{{ props.row.planNum }}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="实际人数">
                            <span>{{ props.row.actNum }}</span>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="0">
                        <el-col :span="6">
                          <el-form-item label="职称">
                            <span>{{ props.row.title }}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="办公电话">
                            <span>{{ props.row.officePhone }}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="联系方式">
                            <span>{{ props.row.telPhone }}</span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="联系邮箱">
                            <span>{{ props.row.email }}</span>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="0">
                        <el-col :span="24">
                          <el-form-item label="备注">
                            <span style="color:red">{{ props.row.remark }}</span>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="0">
                        <el-col :span="6">
                          <el-form-item label="照片">
                            <span><img :src="props.row.face" width="120" height="150"></span>
                          </el-form-item>
                        </el-col>
                        <el-col :span="18">
                          <el-form-item label="导师简介">
                            <span>{{ props.row.introduce }}</span>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>
                  </template>
                </el-table-column>
                <el-table-column type="selection" width="50" v-if="functions['automatic_allocation']"></el-table-column>
                <el-table-column prop="teacherId" label="工号" ></el-table-column>
                <el-table-column label="姓名" >
                  <template slot-scope="props">
                    <span style="cursor:pointer" @click="handleExpansion(props.row)">{{props.row.name}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="性别" >
                  <template slot-scope="props">
                    {{props.row.sex}}
                  </template>
                </el-table-column>
                <el-table-column label="职称" show-overflow-tooltip>
                  <template slot-scope="props">
                    {{props.row.title}}
                    <!-- <el-popover placement="bottom-start"  trigger="hover" :content="props.row.title">
                      <span slot="reference">{{props.row.title}}</span>
                    </el-popover> -->
                  </template>
                </el-table-column>
                <el-table-column label="学院" show-overflow-tooltip>
                  <template slot-scope="props">
                    {{props.row.department}}
                    <!-- <el-popover placement="bottom-start"  trigger="hover" :content="props.row.department">
                      <span slot="reference">{{props.row.department}}</span>
                    </el-popover> -->
                  </template>
                </el-table-column>
                <el-table-column label="专业" show-overflow-tooltip>
                  <template slot-scope="props">
                    {{props.row.subject}}
                    <!-- <el-popover placement="bottom-start"  trigger="hover" :content="props.row.subject">
                      <span slot="reference"></span>
                    </el-popover> -->
                  </template>
                </el-table-column>
                <el-table-column prop="grade" label="年级" ></el-table-column>
                <el-table-column prop="planNum" label="计划人数" ></el-table-column>
                <el-table-column label="实际人数">
                  <template slot-scope="props">
                    {{props.row.actNum}}
                  </template>
                </el-table-column>
                <el-table-column :label="$t('message.remark')" show-overflow-tooltip>
                  <template slot-scope="props">
                    {{props.row.remark}}
                    <!-- <el-popover placement="bottom-start"  trigger="hover" :content="props.row.remark">
                      <span slot="reference">{{props.row.remark}}</span>
                    </el-popover> -->
                  </template>
                </el-table-column>
                <el-table-column :label="$t('message.operating')" >
                  <template slot-scope="scope">
                    <el-button type="text" @click="handleExpansion(scope.row)" size="mini">详情</el-button>
                    <el-button type="text" @click="selectStudent(scope.row)" v-if="functions['assign_student']" size="mini">指定学生</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col>
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryForm.pageNum_" :page-sizes="[20,50,100,500,1000]" :page-size="queryForm.pageSize_" layout="total, sizes, prev, pager, next, jumper" :total="queryForm.total" style="float: right;margin:10px 60px 0 0;">
              </el-pagination>
            </el-col>
          </el-row>
        
      <div>
        <el-dialog title="指定学生" width="60%" :visible.sync="showAddUserToGroupBox">
          <el-form :model="queryForm" ref="queryStudentForm" size="mini" class="">
            <el-row :gutter="20" stylestyle="height: 50px;">
              <el-col :span="12">
                <el-form-item label="年级:">
                  <el-select v-model="queryStudentForm.grade" size="mini">
                    <el-option v-for="item in options.grade" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学院:">
                  <el-select v-model="queryStudentForm.department" size="mini" @change="changeStudentFaculty">
                    <el-option v-for="item in options.college" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="专业:">
                  <el-select v-model="queryStudentForm.subject" size="mini">
                    <el-option v-for="item in options.speciality_student" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item class="float-right">
                  <el-button @click="studentQueryReset" size="mini">重置</el-button>
                  <el-button type="primary" @click="onSelectStudent" size="mini">筛选</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0" style="height: 50px;border-bottom: 1px solid #d2d4d6;">
              <el-col :span="6">
                <el-input type="text" v-model="queryStudentForm.condition" placeholder="学号、姓名" size="mini" @keyup.enter.native="filterStudent">
                  <i class="el-icon-search" slot="suffix" style="margin-top:7px;cursor: pointer;" @click="filterStudent">
                  </i>
                </el-input>
              </el-col>
              <el-col :span="12">
                <div style="line-height:35px;margin-left:10px">导师：{{currentTeacherName}}&nbsp;&nbsp;计划人数：
                  <font style="color:red;">[{{planNum}}]</font>&nbsp;&nbsp;实际人数：
                  <font style="color:red;">[{{actNum}}]</font>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="float-right">
                  <el-button @click="autoAssignStudent" size="mini">自动分配</el-button>
                </div>
              </el-col>
            </el-row>
          </el-form>
          <el-row :gutter="0" class="no-margin">
            <el-col>
              <el-table :data="students" size="mini" @selection-change="chooseStudent" @select="handleCheckbox" @select-all="handleCheckboxAll" ref="studentTable">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="studentId" label="学号" width="100"></el-table-column>
                <el-table-column prop="name" label="姓名" width="100"></el-table-column>
                <el-table-column prop="departmentName" label="学院"></el-table-column>
                <el-table-column prop="professionName" label="专业"></el-table-column>
                <el-table-column prop="trainingLevel" label="培养层次" width="100"></el-table-column>
                <el-table-column width="140" label="联系电话">
                  <template slot-scope="props">
                    {{props.row.phoneNumber}}
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row :gutter="0" style="margin:10px 0;line-height:32px">
            <el-col>
              <div class="float-left">
                <span class="edu-total">总计：{{queryStudentForm.total}}</span>
              </div>
              <div class="float-right">
                <el-pagination layout="prev, pager, next" @size-change="handleStuSizeChange" @current-change="handleStuCurrentChange" :page-size="queryStudentForm.pageSize_" :current-page="queryStudentForm.pageNum_" :total="queryStudentForm.total">
                </el-pagination>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="0" style="margin-top:10px">
            <el-col :span="24">
              <div class="float-right">
                <el-button @click="onCancelDialog" size="mini">取消</el-button>
                <el-button type="primary" @click="onConfirmSelect" size="mini">确定</el-button>
              </div>
            </el-col>
          </el-row>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>
<script>
import {
    findTeacherList,
    findApplyStudentList,
    saveStudentTeacherMap,
    exportTeacherApplyList,
    batchStudentTeacherMap,
    getImageData
} from "common/src/api/teacherinfo";
import { queryDic } from "common/src/api/dictionary";
import fetch from "common/src/utils/fetch";
export default {
    name: "TeacherApplyList",
    data() {
        return {
            defaultPhoto: "/static/images/icon_photo.png",
            queryForm: {
                teacherId: "",
                grade: "",
                department: "",
                subject: "",
                hasQualificataion: "",
                workStatus: "",
                total: 0,
                pageSize_: 20,
                pageNum_: 1,
                remark: ""
            },
            queryStudentForm: {
                condition: "",
                grade: "",
                department: "",
                subject: "",
                total: 0,
                pageSize_: 20,
                pageNum_: 1
            },
            showAddUserToGroupBox: false,
            options: {
                college: [],
                speciality: [],
                speciality_student: [],
                grade: [],
                workStatus: [],
                qualification: []
            },
            teachers: [],
            students: [],
            currentTeacherId: 0,
            chosedTeacher: [],
            chosedStudent: [],
            actNum: 0,
            planNum: 0,
            currentTeacherName: "",
            functions: []
        };
    },
    mounted: function() {
        this.init();
        this.getTeacherList(true);
    },
    created: function() {
        this.$store.getters.getFuncUnderPage(this.$route.path).then(funcs => {
            this.functions = funcs;
        });
    },
    methods: {
        init() {
            let year = new Date().getFullYear();
            for (let i = year; i > year - 6; i--) {
                this.options.grade.push({ label: i, value: i });
            }
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_PYCC", "X_YX"]
            };
            queryDic(data)
                .then(res => {
                    if (res.code == 200) {
                        this._fill("college", res.data.X_YX);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        _fill(type, data) {
            for (let key in data) {
                this.options[type].push({
                    value: key,
                    label: data[key]
                });
            }
        },
        reset() {
            this.queryForm.teacherId = "";
            this.queryForm.grade = "";
            this.queryForm.hasQualificataion = "";
            this.queryForm.workStatus = "";
            this.queryForm.department = "";
            this.queryForm.subject = "";
        },
        studentQueryReset() {
            this.queryStudentForm.grade = "";
            this.queryStudentForm.department = "";
            this.queryStudentForm.subject = "";
        },
        changeFaculty(val) {
            this.options["speciality"] = [];
            this.queryForm.subject = "";
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["G_ZY"],
                filter: {
                    prefix: [val],
                    specilaCode: "XY2ZY"
                }
            };
            queryDic(data)
                .then(res => {
                    if (res.code == 200)
                        this._fill("speciality", res.data.G_ZY);
                })
                .catch(error => {
                    console.log(error);
                });
        },
        changeStudentFaculty(val, callback) {
            this.options["speciality_student"] = [];
            this.queryStudentForm.subject = "";
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["G_ZY"],
                filter: {
                    prefix: [val],
                    specilaCode: "XY2ZY"
                }
            };
            queryDic(data)
                .then(res => {
                    if (res.code == 200) {
                        this._fill("speciality_student", res.data.G_ZY);
                        if (callback) {
                            callback();
                        }
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        onSubmit() {
            this.queryForm.pageNum_ = 1;
            this.getTeacherList(true);
        },
        postAutoAssign(teacherIds) {
            if (teacherIds == "") {
                this.$message({
                    type: "info",
                    message: "请选择要自动分配的导师"
                });
                return;
            }
            let data = {
                teacherId: teacherIds,
                grade: this.queryForm.grade,
                department: this.queryForm.department,
                subject: this.queryForm.subject
            };
            batchStudentTeacherMap(data)
                .then(response => {
                    if (response.code == 200) {
                        this.$message({
                            type: "success",
                            message: "自动分配成功"
                        });
                    } else {
                        throw "自动分配失败";
                    }
                })
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: error
                    });
                });
        },
        //为当前导师分配学生
        autoAssignStudent() {
            this.postAutoAssign(this.currentTeacherId);
        },
        //为当前选中多个导师分配学生
        autoAssignTeacher() {
            let teacherIds = this.chosedTeacher.map(t => t.teacherId).join(",");
            this.postAutoAssign(teacherIds);
        },
        exportFromExcel() {
            document.getElementById("fileUp").click();
        },
        exportToExcel() {
            let params = {
                teacherId: this.queryForm.teacherId,
                grade: this.queryForm.grade,
                name: "",
                department: this.queryForm.department,
                subject: this.queryForm.subject,
                hasQualificataion: this.queryForm.hasQualificataion,
                workStatus: this.queryForm.workStatus,
                "x-token":
                    this.$store.state.session.sessionid ||
                    localStorage.getItem("sessionid") ||
                    ""
            };
            console.log(params);
            let url = exportTeacherApplyList(params);
            window.open(url);
        },
        filter() {
            this.onSubmit();
        },
        filterStudent() {
            this.onSelectStudent();
        },
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val;
            this.getTeacherList();
        },
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val;
            this.getTeacherList();
        },
        handleStuCurrentChange(val) {
            this.queryStudentForm.pageNum_ = val;
            this.getStudentList();
        },
        handleStuSizeChange(val) {
            this.queryStudentForm.pageSize_ = val;
            this.getStudentList();
        },
        comeConfirm() {},
        getTeacherList(showMessage = false) {
            findTeacherList(this.queryForm)
                .then(response => {
                    if (response.code == 200) {
                        response.data.list.forEach(option => {
                            option.face = "";
                        });
                        this.teachers = response.data.list;
                        this.queryForm.total = response.data.total;
                        if (showMessage) {
                            this.$message({
                                type: "success",
                                message: "查询成功"
                            });
                        }
                    } else {
                        throw "查询失败";
                    }
                })
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: "查询失败"
                    });
                });
        },
        getStudentList() {
            findApplyStudentList(this.queryStudentForm)
                .then(response => {
                    if (response.code === 200) {
                        this.students = response.data.list;
                        this.queryStudentForm.total = response.data.total;
                    } else {
                        throw "查询失败";
                    }
                })
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: "查询失败"
                    });
                });
        },
        //指定学生
        selectStudent(row) {
            this.currentTeacherId = row.teacherId;
            this.showAddUserToGroupBox = true;
            this.students = [];
            this.chosedStudent = [];
            this.actNum = row.actNum;
            this.planNum = row.planNum;
            this.currentTeacherName = row.name;

            this.queryStudentForm.total = 0;
            this.queryStudentForm.grade = "";
            this.queryStudentForm.department = "";
            this.queryStudentForm.subject = "";
            this.options.speciality_student = [];
            //指定学生默认查询条件，为当前导师的学院和专业

            let college = this.options.college.find(
                c => c.label == row.department
            );
            if (college) {
                this.queryStudentForm.department = college.value;
                this.changeStudentFaculty(college.value, () => {
                    if (row.subject != null) {
                        this.options.speciality_student.forEach(option => {
                            if (option.label == row.subject) {
                                this.queryStudentForm.subject = option.value;
                            }
                        });
                    }
                    this.onSelectStudent();
                });
            } else {
                this.onSelectStudent();
            }
        },
        //查询学生列表
        onSelectStudent() {
            this.queryStudentForm.pageNum_ = 1;
            this.getStudentList();
        },
        //取消弹框
        onCancelDialog() {
            this.showAddUserToGroupBox = false;
        },
        //确定选择学生
        onConfirmSelect() {
            if (this.chosedStudent.length > 0) {
                saveStudentTeacherMap(
                    this.currentTeacherId,
                    this.chosedStudent.map(s => s.studentId).join(",")
                )
                    .then(response => {
                        if (response.code == 200) {
                            this.$message({
                                type: "success",
                                message: "申请成功"
                            });
                            this.getTeacherList();
                        } else {
                            throw "申请失败";
                        }
                        this.showAddUserToGroupBox = false;
                    })
                    .catch(error => {
                        this.$message({
                            type: "error",
                            message: error
                        });
                    });
            } else {
                this.$message({
                    type: "info",
                    message: "请指定学生"
                });
            }
        },
        //选择学生
        chooseStudent(val) {
            this.chosedStudent = val;
        },
        chooseTeacher(val) {
            this.chosedTeacher = val;
        },
        handleUpload(e) {
            let file = document.getElementById("fileUp").files[0];
            let param = new FormData(); //创建form对象
            param.append("file", file); //通过append向form对象添加数据
            let url = "/api/welcomeservice/teacher/importTeacherList";
            fetch({
                method: "post",
                url: url,
                data: param
            })
                .then(res => {
                    if (res.code == 200) {
                        let msg = "导入成功";
                        if (res.msg != "") {
                            msg = res.msg;
                        }
                        this.$message({
                            type: "success",
                            message: msg
                        });
                        this.getTeacherList();
                    } else {
                        throw res.msg;
                    }
                })
                .catch(err => {
                    this.$message({
                        type: "error",
                        message: err
                    });
                });
        },
        expandChange: function(row, expandedRows) {
            let teacher = this.teachers.find(
                t => t.teacherId == row.teacherId && !t.hasImg
            );
            if (teacher) {
                if (!teacher.hasImg) {
                    teacher.hasImg = true;
                    teacher.face = this.defaultPhoto;
                    if (teacher.photo) {
                        getImageData(teacher.photo)
                            .then(response => {
                                if (response.code == 200 && response.data) {
                                    teacher.face = response.data.base;
                                }
                            })
                            .catch(err => {});
                    }
                }
            } else {
                teacher.face = this.defaultPhoto;
            }
        },
        handleExpansion(row) {
            this.$refs.teacherTable.toggleRowExpansion(row);
        },
        /**
         * 指定学生的复选处理，选中人数不能超过剩余数
         */

        handleCheckbox(selection, row) {
            let remainder = this.planNum - this.actNum; //剩余申请数
            if (selection.length > remainder) {
                this.$refs.studentTable.toggleRowSelection(row, false);
            }
        },
        /**
         * 指定学生的全选处理，选中人数不能超过剩余数
         */
        handleCheckboxAll(selection) {
            let remainder = this.planNum - this.actNum;
            if (selection.length > remainder) {
                this.$refs.studentTable.clearSelection();
                for (let i = 0; i < selection.length && i < remainder; i++) {
                  this.$refs.studentTable.toggleRowSelection(selection[i], true);
                }
            }
        }
    }
};
</script>

<style lang="scss" scoped>
</style>